 <!-- 组织管理 -->
<template>
    <div class="organization-container">
      <!-- 页面标题 -->
      <div class="page-header">
        <div class="title">
          <el-icon><Office /></el-icon>
          <span>组织管理</span>
        </div>
        <div class="actions">
          <el-button type="danger" :disabled="!selectedRows.length" @click="handleBatchDelete">
            <el-icon><Delete /></el-icon>批量删除
          </el-button>
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>新增组织
          </el-button>
        </div>
      </div>
  
      <!-- 搜索区域 -->
      <el-card class="search-card" shadow="hover">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="关键字">
            <el-input v-model="searchForm.keyword" placeholder="组织名称/联系人" clearable />
          </el-form-item>
          <el-form-item label="组织类型">
            <el-select v-model="searchForm.type" placeholder="请选择类型" clearable>
              <el-option label="社会组织" :value="0" />
              <el-option label="政府机构" :value="1" />
              <el-option label="企业" :value="2" />
              <el-option label="学校" :value="3" />
              <el-option label="其他" :value="4" />
            </el-select>
          </el-form-item>
          <el-form-item label="组织级别">
            <el-select v-model="searchForm.level" placeholder="请选择级别" clearable>
              <el-option label="国家级" :value="0" />
              <el-option label="省级" :value="1" />
              <el-option label="市级" :value="2" />
              <el-option label="区县级" :value="3" />
              <el-option label="街道级" :value="4" />
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
              <el-option label="待审核" :value="0" />
              <el-option label="已审核" :value="1" />
              <el-option label="已驳回" :value="2" />
              <el-option label="已禁用" :value="3" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>搜索
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>重置
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
  
      <!-- 表格区域 -->
      <el-card class="table-card" shadow="hover">
        <el-table
          v-loading="loading"
          :data="tableData"
          border
          stripe
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column prop="id" label="ID" width="60" align="center" />
          <el-table-column prop="name" label="组织名称" min-width="120" show-overflow-tooltip />
          <el-table-column prop="type" label="类型" width="100" align="center">
            <template #default="scope">
              {{ getTypeText(scope.row.type) }}
            </template>
          </el-table-column>
          <el-table-column prop="level" label="级别" width="100" align="center">
            <template #default="scope">
              {{ getLevelText(scope.row.level) }}
            </template>
          </el-table-column>
          <el-table-column prop="contactPerson" label="联系人" width="100" align="center" />
          <el-table-column prop="contactPhone" label="联系电话" width="120" align="center" />
          <el-table-column prop="status" label="状态" width="100" align="center">
            <template #default="scope">
              <el-tag :type="getStatusType(scope.row.status)" effect="dark">
                {{ getStatusText(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="160" align="center" />
          <el-table-column label="操作" width="250" align="center" fixed="right">
            <template #default="scope">
              <el-button type="primary" link @click="handleView(scope.row)">
                <el-icon><View /></el-icon>查看
              </el-button>
              <el-button type="success" link @click="handleEdit(scope.row)">
                <el-icon><Edit /></el-icon>编辑
              </el-button>
              <el-button 
                type="warning" 
                link 
                @click="handleReview(scope.row)"
                v-if="scope.row.status === 0"
              >
                <el-icon><Check /></el-icon>审核
              </el-button>
              <el-button 
                type="danger" 
                link 
                @click="handleDelete(scope.row)"
                v-if="scope.row.status !== 3"
              >
                <el-icon><Delete /></el-icon>删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
  
        <!-- 分页 -->
        <div class="pagination">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
  
      <!-- 组织表单对话框 -->
      <el-dialog
        v-model="dialogVisible"
        :title="dialogTitle"
        width="600px"
        :close-on-click-modal="false"
      >
        <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="100px"
          class="organization-form"
        >
          <el-form-item label="组织名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入组织名称" />
          </el-form-item>
          <el-form-item label="组织类型" prop="type">
            <el-select v-model="form.type" placeholder="请选择组织类型">
              <el-option label="社会组织" :value="0" />
              <el-option label="政府机构" :value="1" />
              <el-option label="企业" :value="2" />
              <el-option label="学校" :value="3" />
              <el-option label="其他" :value="4" />
            </el-select>
          </el-form-item>
          <el-form-item label="组织级别" prop="level">
            <el-select v-model="form.level" placeholder="请选择组织级别">
              <el-option label="国家级" :value="0" />
              <el-option label="省级" :value="1" />
              <el-option label="市级" :value="2" />
              <el-option label="区县级" :value="3" />
              <el-option label="街道级" :value="4" />
            </el-select>
          </el-form-item>
          <el-form-item label="联系人" prop="contactPerson">
            <el-input v-model="form.contactPerson" placeholder="请输入联系人姓名" />
          </el-form-item>
          <el-form-item label="联系电话" prop="contactPhone">
            <el-input v-model="form.contactPhone" placeholder="请输入联系电话" />
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="form.email" placeholder="请输入邮箱" />
          </el-form-item>
          <el-form-item label="地址" prop="address">
            <el-input v-model="form.address" placeholder="请输入地址" />
          </el-form-item>
          <el-form-item label="组织简介" prop="description">
            <el-input
              v-model="form.description"
              type="textarea"
              :rows="3"
              placeholder="请输入组织简介"
            />
          </el-form-item>
          <el-form-item label="注册码" prop="registrationCode">
            <el-input v-model="form.registrationCode" placeholder="请输入注册码" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSubmit">确定</el-button>
          </span>
        </template>
      </el-dialog>
  
      <!-- 审核对话框 -->
      <el-dialog
        v-model="reviewDialogVisible"
        title="审核组织"
        width="500px"
        :close-on-click-modal="false"
      >
        <el-form
          ref="reviewFormRef"
          :model="reviewForm"
          :rules="reviewRules"
          label-width="100px"
        >
          <el-form-item label="审核结果" prop="status">
            <el-radio-group v-model="reviewForm.status">
              <el-radio :label="1">通过</el-radio>
              <el-radio :label="2">驳回</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            label="驳回原因"
            prop="rejectReason"
            v-if="reviewForm.status === 2"
          >
            <el-input
              v-model="reviewForm.rejectReason"
              type="textarea"
              :rows="3"
              placeholder="请输入驳回原因"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="reviewDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleReviewSubmit">确定</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script setup>
  import { ref, reactive, onMounted } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import {
    Office,
    Plus,
    Search,
    Refresh,
    Edit,
    View,
    Delete,
    Check
  } from '@element-plus/icons-vue'
  import {
    getOrganizationList,
    registerOrganization,
    updateOrganization,
    deleteOrganization,
    batchDeleteOrganization,
    reviewOrganization,
    getOrganizationDetail
  } from '@/api/organization'
  
  // 加载状态
  const loading = ref(false)
  
  // 搜索表单
  const searchForm = reactive({
    keyword: '',
    type: null,
    level: null,
    status: null
  })
  
  // 表格数据
  const tableData = ref([])
  const currentPage = ref(1)
  const pageSize = ref(10)
  const total = ref(0)
  const selectedRows = ref([])
  
  // 对话框相关
  const dialogVisible = ref(false)
  const dialogTitle = ref('')
  const formRef = ref(null)
  const isView = ref(false)
  
  // 表单数据
  const form = reactive({
    id: '',
    name: '',
    description: '',
    address: '',
    contactPerson: '',
    contactPhone: '',
    email: '',
    type: 0,
    level: 2,
    registrationCode: ''
  })
  
  // 表单验证规则
  const rules = {
    name: [{ required: true, message: '请输入组织名称', trigger: 'blur' }],
    type: [{ required: true, message: '请选择组织类型', trigger: 'change' }],
    level: [{ required: true, message: '请选择组织级别', trigger: 'change' }],
    contactPerson: [{ required: true, message: '请输入联系人姓名', trigger: 'blur' }],
    contactPhone: [
      { required: true, message: '请输入联系电话', trigger: 'blur' },
      { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
    ],
    email: [
      { required: true, message: '请输入邮箱', trigger: 'blur' },
      { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
    ],
    address: [{ required: true, message: '请输入地址', trigger: 'blur' }],
    description: [{ required: true, message: '请输入组织简介', trigger: 'blur' }],
    registrationCode: [{ required: true, message: '请输入注册码', trigger: 'blur' }]
  }
  
  // 审核对话框相关
  const reviewDialogVisible = ref(false)
  const reviewFormRef = ref(null)
  const reviewForm = reactive({
    id: '',
    status: 1,
    rejectReason: '',
    reviewerId: '1' // 这里应该使用实际的审核人ID
  })
  
  // 审核表单验证规则
  const reviewRules = {
    status: [{ required: true, message: '请选择审核结果', trigger: 'change' }],
    rejectReason: [{ required: true, message: '请输入驳回原因', trigger: 'blur' }]
  }
  
  // 获取组织列表
  const fetchData = async () => {
    loading.value = true
    try {
      const res = await getOrganizationList({
        pageNum: currentPage.value,
        pageSize: pageSize.value,
        ...searchForm
      })
      if (res.code === 200) {
        tableData.value = res.data.records
        total.value = res.data.total
      }
    } catch (error) {
      console.error('获取组织列表失败：', error)
      ElMessage.error('获取组织列表失败')
    } finally {
      loading.value = false
    }
  }
  
  // 搜索
  const handleSearch = () => {
    currentPage.value = 1
    fetchData()
  }
  
  // 重置
  const handleReset = () => {
    Object.keys(searchForm).forEach(key => {
      searchForm[key] = null
    })
    handleSearch()
  }
  
  // 新增组织
  const handleAdd = () => {
    dialogTitle.value = '新增组织'
    isView.value = false
    Object.keys(form).forEach(key => {
      form[key] = ''
    })
    dialogVisible.value = true
  }
  
  // 编辑组织
  const handleEdit = (row) => {
    dialogTitle.value = '编辑组织'
    isView.value = false
    Object.keys(form).forEach(key => {
      form[key] = row[key]
    })
    dialogVisible.value = true
  }
  
  // 查看组织
  const handleView = async (row) => {
    dialogTitle.value = '查看组织'
    isView.value = true
    try {
      const res = await getOrganizationDetail(row.id)
      if (res.code === 200) {
        Object.keys(form).forEach(key => {
          form[key] = res.data[key]
        })
        dialogVisible.value = true
      }
    } catch (error) {
      console.error('获取组织详情失败：', error)
      ElMessage.error('获取组织详情失败')
    }
  }
  
  // 删除组织
  const handleDelete = (row) => {
    ElMessageBox.confirm('确认删除该组织吗？', '提示', {
      type: 'warning'
    }).then(async () => {
      try {
        const res = await deleteOrganization(row.id)
        if (res.code === 200) {
          ElMessage.success('删除成功')
          fetchData()
        }
      } catch (error) {
        console.error('删除组织失败：', error)
        ElMessage.error('删除组织失败')
      }
    })
  }
  
  // 批量删除
  const handleBatchDelete = () => {
    if (!selectedRows.value.length) {
      ElMessage.warning('请选择要删除的组织')
      return
    }
    ElMessageBox.confirm('确认删除选中的组织吗？', '提示', {
      type: 'warning'
    }).then(async () => {
      try {
        const ids = selectedRows.value.map(row => row.id)
        const res = await batchDeleteOrganization(ids)
        if (res.code === 200) {
          ElMessage.success('删除成功')
          fetchData()
        }
      } catch (error) {
        console.error('批量删除组织失败：', error)
        ElMessage.error('批量删除组织失败')
      }
    })
  }
  
  // 审核组织
  const handleReview = (row) => {
    reviewForm.id = row.id
    reviewForm.status = 1
    reviewForm.rejectReason = ''
    reviewDialogVisible.value = true
  }
  
  // 提交审核
  const handleReviewSubmit = async () => {
    if (!reviewFormRef.value) return
    await reviewFormRef.value.validate(async (valid) => {
      if (valid) {
        try {
          const res = await reviewOrganization(reviewForm.id, {
            status: reviewForm.status,
            rejectReason: reviewForm.rejectReason,
            reviewerId: reviewForm.reviewerId
          })
          if (res.code === 200) {
            ElMessage.success('审核成功')
            reviewDialogVisible.value = false
            fetchData()
          }
        } catch (error) {
          console.error('审核组织失败：', error)
          ElMessage.error('审核组织失败')
        }
      }
    })
  }
  
  // 提交表单
  const handleSubmit = async () => {
    if (!formRef.value) return
    await formRef.value.validate(async (valid) => {
      if (valid) {
        try {
          const api = form.id ? updateOrganization : registerOrganization
          const res = await api(form)
          if (res.code === 200) {
            ElMessage.success(form.id ? '更新成功' : '添加成功')
            dialogVisible.value = false
            fetchData()
          }
        } catch (error) {
          console.error('提交表单失败：', error)
          ElMessage.error('提交表单失败')
        }
      }
    })
  }
  
  // 表格选择
  const handleSelectionChange = (rows) => {
    selectedRows.value = rows
  }
  
  // 分页
  const handleSizeChange = (val) => {
    pageSize.value = val
    fetchData()
  }
  
  const handleCurrentChange = (val) => {
    currentPage.value = val
    fetchData()
  }
  
  // 获取类型文本
  const getTypeText = (type) => {
    const types = {
      0: '社会组织',
      1: '政府机构',
      2: '企业',
      3: '学校',
      4: '其他'
    }
    return types[type] || '未知'
  }
  
  // 获取级别文本
  const getLevelText = (level) => {
    const levels = {
      0: '国家级',
      1: '省级',
      2: '市级',
      3: '区县级',
      4: '街道级'
    }
    return levels[level] || '未知'
  }
  
  // 获取状态类型
  const getStatusType = (status) => {
    const types = {
      0: 'warning',   // 待审核
      1: 'success',   // 已审核
      2: 'danger',    // 已驳回
      3: 'info'       // 已禁用
    }
    return types[status] || 'info'
  }
  
  // 获取状态文本
  const getStatusText = (status) => {
    const texts = {
      0: '待审核',
      1: '已审核',
      2: '已驳回',
      3: '已禁用'
    }
    return texts[status] || '未知'
  }
  
  // 页面初始化
  onMounted(() => {
    fetchData()
  })
  </script>
  
  <style scoped>
  .organization-container {
    padding: 24px;
    background-color: #f0f2f5;
    min-height: 100%;
  }
  
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    background: linear-gradient(135deg, #1890ff 0%, #36cfc9 100%);
    padding: 24px;
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(24, 144, 255, 0.15);
  }
  
  .title {
    display: flex;
    align-items: center;
    font-size: 24px;
    font-weight: 600;
    color: #fff;
  }
  
  .title .el-icon {
    margin-right: 12px;
    font-size: 28px;
  }
  
  .actions {
    display: flex;
    gap: 12px;
  }
  
  .search-card {
    margin-bottom: 24px;
  }
  
  .search-form {
    display: flex;
    flex-wrap: wrap;
    gap: 16px;
  }
  
  .table-card {
    margin-bottom: 24px;
  }
  
  .pagination {
    margin-top: 24px;
    display: flex;
    justify-content: flex-end;
  }
  
  .organization-form {
    padding: 20px;
  }
  
  .avatar-uploader,
  .license-uploader {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }
  
  .avatar-uploader:hover,
  .license-uploader:hover {
    border-color: var(--el-color-primary);
  }
  
  .avatar-uploader-icon,
  .license-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    text-align: center;
    line-height: 100px;
  }
  
  .avatar {
    width: 100px;
    height: 100px;
    display: block;
    object-fit: cover;
  }
  
  .license {
    width: 200px;
    height: 100px;
    display: block;
    object-fit: cover;
  }
  
  :deep(.el-form-item__content) {
    flex-wrap: nowrap;
  }
  
  :deep(.el-input) {
    width: 200px;
  }
  
  :deep(.el-select) {
    width: 160px;
  }
  </style>